<template>
  <div class="salary-page">

    <el-form :inline="true" :model="filters" class="filter-form" @submit.prevent>
      <el-form-item label="发放状态" style="min-width: 180px;">
        <el-select v-model="filters.status" placeholder="全部" clearable style="width: 140px;">
          <el-option label="未审核" :value="0" />
          <el-option label="已发放" :value="1" />
          <el-option label="未发放" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生姓名">
        <el-input v-model="filters.studentName" placeholder="输入学生姓名" clearable />
      </el-form-item>
      <el-form-item label="教师姓名">
        <el-input v-model="filters.teacherName" placeholder="输入教师姓名" clearable />
      </el-form-item>
      <el-form-item label="岗位名称">
        <el-input v-model="filters.positionName" placeholder="输入岗位名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData" :icon="Search">查询</el-button>
        <el-button @click="resetFilters" :icon="Refresh">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right;margin-left:auto;">
        <el-button 
          type="success" 
          @click="handleBatchAudit" 
          :disabled="!hasUnauditedSelection"
        >
          批量通过
        </el-button>
      </el-form-item>
    </el-form>
    
    <div class="salary-table-wrapper">
      <el-table 
        :data="tableData.records" 
        style="width: 100%;" 
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="row => row.status === 0" fixed="left" />
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="teacherName" label="教师姓名" width="120" />
        <el-table-column prop="positionName" label="岗位名称" show-overflow-tooltip min-width="150" />
        <el-table-column prop="totalHour" label="总工时" width="120">
          <template #default="{ row }">
            {{ row.totalHour }} 小时
          </template>
        </el-table-column>
        <el-table-column prop="totalSalary" label="总工资" width="120">
          <template #default="{ row }">
            {{ row.totalSalary }} 元
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" effect="plain">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 0" 
              size="small" 
              type="success" 
              @click="handleAudit(row)"
            >
              通过
            </el-button>
            <el-button 
              v-if="row.status === 0" 
              size="small" 
              type="danger" 
              @click="handleReject(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="tableData.total"
        :page-size="filters.size"
        :current-page="filters.page"
        @current-change="handlePageChange"
      />
    </div>
    
    <!-- 审核弹窗 -->
    <el-dialog v-model="auditDialogVisible" :title="auditForm.status === 1 ? '审核通过' : '审核拒绝'" width="400px">
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAuditSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listSalaries, auditSalary, batchAuditSalary } from '@/api/salary'
import { Delete, Edit, Search, Plus, Refresh } from '@element-plus/icons-vue'

interface ApiResponse<T> {
  code: number
  data: T
  msg?: string
}

interface SalaryRecord {
  id: number
  studentName: string
  teacherName: string
  positionName: string
  totalHour: number
  totalSalary: number
  status: number
  createTime: string
}

interface TableData {
  records: SalaryRecord[]
  total: number
}

interface Filters {
  status: number | null
  studentName: string
  teacherName: string
  positionName: string
  page: number
  size: number
}

const filters = ref<Filters>({
  status: null,
  studentName: '',
  teacherName: '',
  positionName: '',
  page: 1,
  size: 8
})

const tableData = ref<TableData>({
  records: [],
  total: 0
})

const selectedRows = ref<SalaryRecord[]>([])
const auditDialogVisible = ref(false)
const auditForm = reactive({
  id: null as number | null,
  status: 1
})

const hasUnauditedSelection = computed(() => {
  return selectedRows.value.length > 0 && selectedRows.value.every(row => row.status === 0)
})

const fetchData = async () => {
  try {
    const res = await listSalaries(filters.value)
    if (res.data) {
      tableData.value = {
        records: res.data.records,
        total: res.data.total
      }
      filters.value.page = res.data.current
      filters.value.size = res.data.size
    }
  } catch (e) {
    ElMessage.error('获取工资列表失败')
  }
}

const handlePageChange = (val: number) => {
  filters.value.page = val
  fetchData()
}

const resetFilters = () => {
  filters.value = {
    status: null,
    studentName: '',
    teacherName: '',
    positionName: '',
    page: 1,
    size: 8
  }
  fetchData()
}

const handleSelectionChange = (rows: SalaryRecord[]) => {
  selectedRows.value = rows
}

const handleAudit = (row: SalaryRecord) => {
  auditForm.id = row.id
  auditForm.status = 1
  auditDialogVisible.value = true
}

const handleReject = (row: SalaryRecord) => {
  auditForm.id = row.id
  auditForm.status = 2
  auditDialogVisible.value = true
}

const handleBatchAudit = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要审核的记录')
    return
  }

  // 检查是否所有选中的记录都是未审核状态
  if (!selectedRows.value.every(row => row.status === 0)) {
    ElMessage.warning('只能批量审核未审核状态的记录')
    return
  }
  
  ElMessageBox.confirm('确定要批量审核通过选中的记录吗？', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id).join(',')
      const res = (await batchAuditSalary({ ids, status: 1 })) as unknown as ApiResponse<any>
      if (res.code === 0) {
        ElMessage.success('批量审核成功')
        fetchData()
        selectedRows.value = []
      }
    } catch (e) {
      ElMessage.error('批量审核失败')
    }
  })
}

const handleAuditSubmit = async () => {
  try {
    const res = (await auditSalary(auditForm)) as unknown as ApiResponse<any>
    if (res.code === 0) {
      ElMessage.success(auditForm.status === 1 ? '审核通过成功' : '审核拒绝成功')
      auditDialogVisible.value = false
      fetchData()
    }
  } catch (e) {
    ElMessage.error(auditForm.status === 1 ? '审核通过失败' : '审核拒绝失败')
  }
}

const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '未审核'
    case 1:
      return '已发放'
    case 2:
      return '未发放'
    default:
      return '未知'
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.salary-page {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.filter-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.salary-table-wrapper {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  min-height: 500px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table) {
  border-radius: 8px;
  --el-table-border-color: var(--el-border-color-lighter);
}

:deep(.el-table th) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-input) {
  border-radius: 4px;
}

:deep(.el-select) {
  border-radius: 4px;
}

:deep(.el-pagination) {
  justify-content: center;
  width: 100%;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-button--primary) {
  --el-button-hover-bg-color: var(--el-color-primary-light-3);
  --el-button-hover-border-color: var(--el-color-primary-light-3);
}

:deep(.el-button--success) {
  --el-button-hover-bg-color: var(--el-color-success-light-3);
  --el-button-hover-border-color: var(--el-color-success-light-3);
}

:deep(.el-button--danger) {
  --el-button-hover-bg-color: var(--el-color-danger-light-3);
  --el-button-hover-border-color: var(--el-color-danger-light-3);
}
</style>